#define _CRT_SECURE_NO_WARNINGS 1
#include"SeqList.h"

//初始化
void SLInit(SL* ps)
{
	assert(ps);//指针不能为空时非常有用

	ps->a = (SLDataType*)malloc(sizeof(SLDataType) * INIT_CAPACITY);
	if (ps->a == NULL)
	{
		perror("malloc fail");
		return;
	}

	ps->size = 0;
	ps->capacity = INIT_CAPACITY;
}

//销毁
void SLDestroy(SL* ps)
{
	assert(ps);

	free(ps->a);
	ps->a = NULL;
	ps->capacity = ps->size = 0;
}


//打印
void SLPrint(SL* ps)
{
	assert(ps);

	for (int i = 0; i < ps->size; ++i)
	{
		printf("%d ", ps->a[i]);
	}
	printf("\n");
}


//扩容
void SLCheckCapacity(SL* ps)
{
	assert(ps);
	//SLDataType* tmp = (SLDataType*)realloc(ps->a,  ps->capacity * 2);
	SLDataType* tmp = (SLDataType*)realloc(ps->a, sizeof(SLDataType) * ps->capacity * 2);
	if (tmp == NULL)
	{
		perror("realloc fail");
		return;
	}

	ps->a = tmp;
	ps->capacity *= 2;
}


//尾插
void SLPushBack(SL* ps, SLDataType x)
{
	assert(ps);

	// 扩容
	
		SLCheckCapacity(ps);
	

	//ps->a[ps->size] = x;
	//ps->size++;
	//等价于上面两个等式
	ps->a[ps->size++] = x;
}

//尾删
void SLPopBack(SL* ps)
{
	assert(ps);

	// 暴力检查
	assert(ps->size > 0);

	// 温柔的检查
	//if (ps->size == 0)
		//return;

	//ps->a[ps->size - 1] = 0;
	ps->size--;
}

//头插头删

//整体向后挪动数据，当end指针指向下标为-1时结束
//数据往后挪时，前一个数据会把后面一个数据覆盖掉，——会导致越界（扩容解决）
void SLPushFront(SL* ps, SLDataType x)
{
	assert(ps);

	//扩容
	SLCheckCapacity(ps);

	int end = ps->size-1;
	while (end >= 0)
	{
		ps->a[end + 1] = ps->a[end];
		--end;
	}
	ps->a[0] = x;
	ps->size++;

}

//头删，从前往后删，否则数据会被覆盖
void SLPopFront(SL* ps)
{
	assert(ps);
	assert(ps->size > 0);
	
	int begin = 0;
	while (begin<ps->size)
	{
		ps->a[begin - 1] = ps->a[begin];
		++begin;
	}
	ps->size--;
}

//任意pos位置插入，pos在begin和size之间
//顺序表没有缩容的概念，仅是数据的挪动
//有了Insert，可以替代尾插 SLInsert（ps，ps->size,x), 头插 SLInsert（ps，0,x) 
void SLInsert(SL* ps, int pos, SLDataType x)
{
	assert(ps);
	assert(pos >= 0 && pos <= ps->size);
	SLCheckCapacity(ps);

	int end = ps->size - 1;
	while (end >= pos)
	{
		ps->a[end + 1] = ps->a[end];
		--end;
	}
	ps->a[pos] = x;
	ps->size++;
}

//尾删==
//void SLPopBack(SL* ps)
//{
//	SLErase(ps, ps->size - 1);
//}

void SLErase(SL* ps, int pos)
{
	assert(ps);
	//区别于Insert小于等于
	assert(pos >= 0 && pos < ps->size);

	int begin = pos + 1;
	while (begin < ps->size)
	{
		ps->a[begin - 1] = ps->a[begin];
		++begin;
	}
	ps->size--;
}


//通讯录应该的用法
int SLFind(SL* ps, SLDataType x)
{
	assert(ps);
	for (int i = 0; i < ps->size; i++)
	{
		if (ps->a[i] == x)
		{
			return i;	
		}
	}
	return -1;
}
